package keeto.com.vn.classified.network;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classified.config.IConfig;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.network.entity.CommentEntity;
import keeto.com.vn.classified.network.entity.ListItemEntity;
import keeto.com.vn.classified.network.entity.PromotionHomeEntity;
import keeto.com.vn.classified.network.entity.RatingInfo;
import keeto.com.vn.classified.network.entity.RatingUserEntity;
import keeto.com.vn.classified.request.AckLogonCompleteRequest;
import keeto.com.vn.classified.request.ChangeAvatarRequest;
import keeto.com.vn.classified.request.ChangePassRequest;
import keeto.com.vn.classified.request.CommentRequest;
import keeto.com.vn.classified.request.CommentRequestProduct;
import keeto.com.vn.classified.request.ForgetPassRequest;
import keeto.com.vn.classified.request.GetAndroidInterestShopRequest;
import keeto.com.vn.classified.request.GetAndroidProductProposedRequest;
import keeto.com.vn.classified.request.GetAndroidProductTypeRequest;
import keeto.com.vn.classified.request.GetMyHandBookRequest;
import keeto.com.vn.classified.request.GetProductAdRequest;
import keeto.com.vn.classified.request.GetProductCateFourRequest;
import keeto.com.vn.classified.request.GetProfileInfoRequest;
import keeto.com.vn.classified.request.GetSearchGlobalProductRequest;
import keeto.com.vn.classified.request.LogoutRequest;
import keeto.com.vn.classified.request.ProductBySellerRequest;
import keeto.com.vn.classified.request.PublishRequest;
import keeto.com.vn.classified.request.RegisterRequest;
import keeto.com.vn.classified.request.SendAndroidInterestShopRequest;
import keeto.com.vn.classified.request.SendAndroidProductAbuselRequest;
import keeto.com.vn.classified.request.UpdateUserInfoRequest;
import keeto.com.vn.classified.request.UploadPictureRequest;
import keeto.com.vn.classified.request.ValidateUserRequest;
import keeto.com.vn.classified.response.AckLogonCompleteResponse;
import keeto.com.vn.classified.response.ChangeAvatarResponse;
import keeto.com.vn.classified.response.ChangePassResponse;
import keeto.com.vn.classified.response.CommentResponse;
import keeto.com.vn.classified.response.CommentResponseProduct;
import keeto.com.vn.classified.response.ForgotPassResponse;
import keeto.com.vn.classified.response.GetAndroidInterestShopResponse;
import keeto.com.vn.classified.response.GetAndroidProductResponse;
import keeto.com.vn.classified.response.GetAndroidProductTypeResponse;
import keeto.com.vn.classified.response.GetMyHandBookResponse;
import keeto.com.vn.classified.response.GetProductAdResponse;
import keeto.com.vn.classified.response.GetProductCateFourResponse;
import keeto.com.vn.classified.response.GetProfileInfoResponse;
import keeto.com.vn.classified.response.LogoutResponse;
import keeto.com.vn.classified.response.ProductBySellerRespone;
import keeto.com.vn.classified.response.PublishResponse;
import keeto.com.vn.classified.response.RegisterResponse;
import keeto.com.vn.classified.response.SearchResponse;
import keeto.com.vn.classified.response.SendAndroidInterestShopResponse;
import keeto.com.vn.classified.response.SendAndroidProductAbuselResponse;
import keeto.com.vn.classified.response.UpdateUserInfoResponse;
import keeto.com.vn.classified.response.UploadPictureResponse;
import keeto.com.vn.classified.response.ValidateUserResponse;
import keeto.com.vn.classified.ui.MainApplication;
import keeto.com.vn.classified.utils.Base64;
import keeto.com.vn.classified.utils.MD5Hash;
import keeto.com.vn.classified.utils.StringUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

public class JSONProtocol implements IProtocol {
	public static final int PROGRESS_SIZE = 4096;

	private DefaultHttpClient httpclient;
	private Context ctx;
	private String authKey;
	private String additionStr = "addition";
	private CookieStore cookieStore;
	private ClassifiedCore core;

	public JSONProtocol(Context context, ClassifiedCore core) {
		this.ctx = context;
		this.core = core;
	}

	public boolean checkAddition(JSONObject requestObject) {
		if (IConfig.USE_ADDITION_REQUEST) {
			if (!core.isAckLogon()) {
				return false;
			}
			synchronized (core.isAdditionStatus()) {
				if (core.isAdditionStatus()) {
					core.setAdditionStatus(false);
					try {
						requestObject.put(additionStr, true);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
			return true;
		}
		return false;
	}

	private synchronized String httpPost(String url, String postData)
			throws ClientProtocolException, IOException {

		String responseStr = "";
		HttpResponse response = null;
		HttpEntity entity = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
			nameValues.add(new BasicNameValuePair("json", postData));
			httpPost.setHeader("Content-Type",
					"application/x-www-form-urlencoded");
			httpPost.setHeader("Security-Code",
					"UeUv8W1bR1GQ1BPhkx986426aywDXoLiyjx1BMnebo");
			httpPost.setEntity(new UrlEncodedFormEntity(nameValues, HTTP.UTF_8));
			if (ClassifiedCore.isNetworkfail()) {
				throw new UnsupportedEncodingException();
			}
			if (IConfig.DEBUG_MODE)
				System.out.println("***% request: json=" + postData);
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					IConfig.TIMEOUT_SOCKET);
			HttpConnectionParams.setSoTimeout(httpParams,
					IConfig.TIMEOUT_SOCKET);
			HttpConnectionParams.setSocketBufferSize(httpParams, 2048);
			httpclient = new DefaultHttpClient(httpParams);
			if (cookieStore != null) {
				httpclient.setCookieStore(cookieStore);
			}
			response = httpclient.execute(httpPost);
			if (cookieStore == null) {
				cookieStore = httpclient.getCookieStore();
			}
			entity = response.getEntity();
			InputStream inputStream = entity.getContent();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length = -1;
			while (-1 != (length = inputStream.read(buffer))) {
				bos.write(buffer, 0, length);
			}
			if (entity != null) {
				entity.consumeContent();
			}
			byte[] strBytes = bos.toByteArray();
			responseStr = new String(strBytes);
			Log.d("httpPost", responseStr);
			if (IConfig.DEBUG_MODE)
				System.out.println("***# Response = " + responseStr);
		} catch (ConnectTimeoutException e) {
			Log.e("JSONProtocol 1070", e.getMessage());
			throw new ClientProtocolException();
		} catch (SocketTimeoutException e) {
			Log.e("JSONProtocol 1073", e.getMessage());
			throw new ClientProtocolException();
		} catch (SocketException e) {
			Log.e("JSONProtocol 1076", e.getMessage());
			throw new ClientProtocolException();
		} catch (UnsupportedEncodingException e) {
			Log.e("JSONProtocol 1079", e.getMessage());
			throw new ClientProtocolException();
		} catch (ClientProtocolException e) {
			Log.e("JSONProtocol 1082", e.getMessage());
			throw e;
		}
		return responseStr;
	}

	public static String getJSONRequest(JSONObject requestObject) {
		return StringUtil.URLencode(Base64.encodeToString(requestObject
				.toString().getBytes(), false));
	}

	public static String callServicePostMethod(String url, String strPostObj) {
		StringBuilder builder = new StringBuilder();
		HttpClient httpClient = new DefaultHttpClient();
		String responseStr = "";
		// Log.i("callServicePostMethod URL", url);
		HttpPost httpPost = new HttpPost(url);
		try {
			StringEntity se = new StringEntity(strPostObj, HTTP.UTF_8);
			httpPost.setEntity(se);
			httpPost.setHeader("Content-Type",
					"application/x-www-form-urlencoded");
			httpPost.setHeader("Security-Code",
					"UeUv8W1bR1GQ1BPhkx986426aywDXoLiyjx1BMnebo");
			HttpResponse httpRes = httpClient.execute(httpPost);
			if (httpRes.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpRes.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content), 8192);
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				responseStr = builder.toString();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// Log.i("callServicePostMethod Response", responseStr);
		return responseStr;
	}

	public static String callServiceGetMethod(String url) {
		StringBuilder response = new StringBuilder();

		// Log.i("callServiceGetMethod URL", url);
		try {
			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			conn.setConnectTimeout(15000);
			int timeoutSocket = 10000;
			// HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
			conn.setReadTimeout(timeoutSocket);

			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader input = new BufferedReader(
						new InputStreamReader(conn.getInputStream()), 8192);
				String line = null;
				while ((line = input.readLine()) != null) {
					response.append(line);
				}
				input.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
		// Log.i("callServiceGetMethod Response", response.toString());
		return response.toString();
	}

	@Override
	public GetProductAdResponse getAndroidProductAd(GetProductAdRequest request)
			throws JSONException, ClientProtocolException, IOException {
		GetProductAdResponse response = new GetProductAdResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", "searchAndroidClassifiedAdProduct");
		requestObject.put("AuthKey", "");
		requestObject.put("AreaIds", "1");
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("CategoryType", "products");
		requestObject.put("SortBy", request.getSortBy());
		requestObject.put("Keywords", "");
		requestObject.put("CategoryId", "");
		requestObject.put("pageNumber", request.getPageNumber());
		requestObject.put("AreaIds", request.getArea());
		Log.e("GetAndroidProductAd", "content = " + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("GetAndroidProductAd", "response: " + strResponse);
		JSONObject responseObject = new JSONObject(strResponse);
		response.setReturnCode(responseObject.optInt("Returncode"));
		response.setPageCount(responseObject.optInt("countPage"));
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			JSONArray jsonArray = new JSONArray();
			jsonArray = responseObject.getJSONArray("data");
			ArrayList<ListItemEntity> list = new ArrayList<ListItemEntity>();
			if (jsonArray != null) {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObj = jsonArray.getJSONObject(i);
					ListItemEntity item = parserListItemEntity(jsonObj);
					list.add(item);
				}
				if (request.getSortBy().equals("1")) {
					response.setList_latest(list);
				}
				if (request.getSortBy().equals("3")) {
					response.setList_interest(list);
				}
				if (request.getSortBy().equals("2")) {
					response.setList_appreciate(list);
				}
			}

		}
		return response;
	}

	private CommentEntity parserCommentEntity(JSONObject adJO) {
		CommentEntity ade = new CommentEntity();
		String value = null;
		value = adJO.optString("UserCommentName");
		if (value != null) {
			ade.setUserCommentName(value);
		}

		int rating = adJO.optInt("Rating");
		if (rating >= 0) {
			ade.setRating(rating);
		}
		value = adJO.optString("UserAvatar");
		if (value != null) {
			ade.setUserAvatar(value);
		}
		value = adJO.optString("CommentContent");
		if (value != null) {
			ade.setCommentContent(value);
		}

		value = adJO.optString("CommentDate");
		if (value != null && !value.equals("null")) {
			ade.setCommentDate(value);
		} else {
			ade.setCommentDate("");
		}

		value = adJO.optString("CommentTitle");
		if (value != null && !value.equals("null")) {
			ade.setCommentTitle(value);
		} else {
			ade.setCommentTitle("");
		}

		return ade;
	}

	private ListItemEntity parserListItemEntity(JSONObject adJO) {
		ListItemEntity ade = new ListItemEntity();
		String value = null;
		value = adJO.optString("RemoteId");
		if (value != null) {
			ade.setRemoteId(value);
		}
		value = adJO.optString("Link");
		if (value != null) {
			ade.setLink(value);
		}

		// get AreaIds
		JSONArray array = adJO.optJSONArray("AreaIds");
		if (array != null && array.length() > 0) {
			Area[] areas = new Area[array.length()];
			JSONObject tempObj = null;
			for (int i = 0; i < array.length(); i++) {
				tempObj = array.optJSONObject(i);
				Area tempArea = new Area();
				tempArea.setRemoteId(tempObj.optString("Id"));
				tempArea.setName(tempObj.optString("Name"));
				areas[i] = tempArea;
			}
			ade.setAreas(areas);
		}

		value = adJO.optString("Title");
		if (value != null) {
			ade.setTitle(value);
		}
		value = adJO.optString("Description");
		if (value != null && !value.equals("null")) {
			ade.setDescription(value);
		} else {
			ade.setDescription("");
		}

		value = adJO.optString("Introduct");
		if (value != null && !value.equals("null")) {
			ade.setIntroduct(value);
		} else {
			ade.setIntroduct("");
		}
		value = adJO.optString("SubDesc");
		if (value != null && !value.equals("null")) {
			ade.setSubDec(value);
		} else {
			ade.setSubDec("");
		}

		value = adJO.optString("AdditionalPrice");
		if (value != null && !value.equals("null")) {
			ade.setAdditionPrice(value);
		} else {
			ade.setAdditionPrice("");
		}

		value = adJO.optString("Price");
		if (value != null) {
			ade.setPrice(value);
		}
		long valuelong = adJO.optLong("PublishTime");
		if (valuelong != 0) {
			ade.setPublishTime(valuelong * 1000);
		}

		int valueint = adJO.optInt("Sort");
		ade.setSort(valueint);

		valueint = adJO.optInt("PCode");
		ade.setPcode(valueint);

		value = adJO.optString("CategoryId");
		if (value != null) {
			ade.setCategoryId(value);
		}
		value = adJO.optString("CategoryName");
		if (value != null) {
			ade.setCategoryName(value);
		}
		value = adJO.optString("CategoryParentID");
		if (value != null && !value.equals("null")) {
			ade.setCategoryParentID(value);
		} else {
			ade.setCategoryParentID("");
		}
		value = adJO.optString("CategoryParentName");
		if (value != null && !value.equals("null")) {
			ade.setCategoryParentName(value);
		} else {
			ade.setCategoryParentName("");
		}
		int valuewarranty = 0;
		String warranty = "";
		warranty = adJO.optString("Warranty");
		if (warranty != null && !warranty.equals("")
				&& !warranty.equals("null")) {
			try {
				valuewarranty = Integer.parseInt(warranty.trim());

			} catch (Exception e) {
				// TODO: handle exception
			}
			ade.setWarrantyProduct(valuewarranty);
		} else {
			ade.setWarrantyProduct(0);
		}

		value = adJO.optString("Status");
		if (value != null && !value.equals("null")) {
			ade.setStatus(value);
		} else {
			ade.setStatus("");
		}

		value = adJO.optString("CoverPicture");
		JSONObject pictureJO = adJO.optJSONObject("CoverPicture");
		if (pictureJO != null) {
			ArrayList<String> pictureList = new ArrayList<String>();
			value = pictureJO.optString("Images1");
			if (value != null && value.length() > 0) {
				pictureList.add(value);
			}
			value = pictureJO.optString("Images2");
			if (value != null && value.length() > 0) {
				pictureList.add(value);
			}
			value = pictureJO.optString("Images3");
			if (value != null && value.length() > 0) {
				pictureList.add(value);
			}
			value = pictureJO.optString("Images4");
			if (value != null && value.length() > 0) {
				pictureList.add(value);
			}
			value = pictureJO.optString("Images5");
			if (value != null && value.length() > 0) {
				pictureList.add(value);
			}
			ade.setCoverPicture(pictureList);
		}

		value = adJO.optString("SellerId");
		if (value != null)
			ade.setSellerId(value);
		value = adJO.optString("SellerUsername");
		if (value != null)
			ade.setSellerUsername(value);
		value = adJO.optString("SellerPhone");
		if (value != null)
			ade.setSellerPhone(value);
		value = adJO.optString("SellerEmail");
		if (value != null)
			ade.setSellerEmail(value);
		value = adJO.optString("Publisher");
		if (value != null)
			ade.setPublisher(value);
		value = adJO.optString("DownloadUrl");
		if (value != null)
			ade.setDownloadUrl(value);
		value = adJO.optString("AlbumName");
		if (value != null)
			ade.setAlbumName(value);
		value = adJO.optString("SingerName");
		if (value != null)
			ade.setSingerName(value);
		value = adJO.optString("State");
		if (value != null)
			ade.setState(value);

		valueint = adJO.optInt("DowloadCount");
		ade.setDowloadCount(valueint);

		valueint = adJO.optInt("Rating");
		ade.setRating(valueint);

		ade.setFavorite(adJO.optBoolean("IsFavorite"));

		valueint = adJO.optInt("HasPicture");
		ade.setHasPicture(valueint == 1 ? true : false);
		valueint = adJO.optInt("IsSupperUser");
		ade.setUserLevel(valueint);
		valueint = adJO.optInt("GuaranteeValue");
		ade.setGuaranteeValue(valueint);

		value = adJO.optString("GuaranteeStoreID");
		if (value != null && !value.equals("") && !value.equals("null")) {
			ade.setGuaranteeStoreID(Integer.parseInt(value));
		}
		valueint = adJO.optInt("Discount");
		ade.setDiscount(valueint);
		value = adJO.optString("GuaranteeStoreName");
		if (value != null) {
			ade.setGuaranteeStoreName(value);
		}
		valueint = adJO.optInt("TotalRate");
		ade.setTotalRate(valueint);

		JSONObject additionsJO = adJO.optJSONObject("Additions");

		if (additionsJO != null) {
			Hashtable<String, String> addtions = new Hashtable<String, String>();
			JSONArray names = additionsJO.names();
			for (int i = 0; i < names.length(); i++) {
				String name = names.optString(i);
				String v = additionsJO.optString(name);
				if ((name != null) && (v != null)) {
					addtions.put(name, v);
				}
			}
			ade.setAdditions(addtions);
		}

		JSONObject promotionInfo = adJO.optJSONObject("Promotion");

		if (promotionInfo != null) {
			PromotionHomeEntity promotionentity = new PromotionHomeEntity();

			value = promotionInfo.optString("Name");
			if (value != null && !value.equals("null") && !value.equals("")) {
				promotionentity.setNamePromotion(value);
			}
			value = promotionInfo.optString("DateStart");
			if (value != null && !value.equals("null") && !value.equals("")) {
				promotionentity.setDateStart(value);
			}
			value = promotionInfo.optString("DateEnd");
			if (value != null && !value.equals("null") && !value.equals("")) {
				promotionentity.setDateEnd(value);
			}
			value = promotionInfo.optString("TypeDiscount");
			if (value != null && !value.equals("null") && !value.equals("")) {
				promotionentity.setTypeDiscount(value);
			}
			value = promotionInfo.optString("Discount");
			if (value != null && !value.equals("null") && !value.equals("")) {
				promotionentity.setDiscount(value);
			}
			value = promotionInfo.optString("Intro");
			if (value != null && !value.equals("null") && !value.equals("")) {
				promotionentity.setIntro(value);
			}
			ade.setLisPromotionHomeEntities(promotionentity);
		}

		return ade;
	}

	@Override
	public ValidateUserResponse getLogin(ValidateUserRequest request) {
		// TODO Auto-generated method stub
		ValidateUserResponse response = new ValidateUserResponse();
		JSONObject requestObject = new JSONObject();
		try {
			requestObject.put("actionType", METHOD_LOGON);
			requestObject.put("Username", request.getUsername());
			String password = MD5Hash.convertPwd(request.getPassword());
			requestObject.put("Password", password);
			Log.e("TEST", "logon content= " + requestObject.toString());
			String strResponse = callServicePostMethod(URL, "content="
					+ requestObject.toString());
			Log.e("TEST", "logon response= " + strResponse);
			JSONObject responseObject = new JSONObject(strResponse);
			response.setReturnCode(responseObject.getInt("Returncode"));
			if (response.getReturnCode() == STATUS_CODE_OK_200) {
				String value = "";
				value = responseObject.getString("AuthKey");
				response.setAuthKey(value);
				value = responseObject.getString("DisplayName");
				response.setDisplayName(value);
				value = responseObject.getString("Status");
				response.setStatus(value);
				value = responseObject.getString("Id");
				response.setId(value);
				value = responseObject.getString("SuperUser");
				response.setSuperUser(value);
				value = responseObject.getString("avatar");
				response.setAvatar(value);
				value = responseObject.getString("AreaID");
				response.setAreaId(value);
				value = responseObject.getString("Gender");
				response.setGender(value);
				value = responseObject.getString("Email");
				response.setEmail(value);
				value = responseObject.getString("Mobile");
				response.setMobile(value);

			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return response;
	}

	@Override
	public AckLogonCompleteResponse ackLogonComplete(
			AckLogonCompleteRequest request) {
		AckLogonCompleteResponse response = new AckLogonCompleteResponse();

		JSONObject requestObject = new JSONObject();

		try {
			requestObject.put("method", METHOD_LOGON);

			JSONObject paramsObject = new JSONObject();
			paramsObject.put("AuthKey", request.getAuthKey());
			requestObject.put("params", paramsObject);
			String jsonString = getJSONRequest(requestObject);
			String strResponse = callServicePostMethod(SYNC_URL, jsonString);
			Log.d("AckLogonCompleteResponse", strResponse);
			JSONObject responseObject = new JSONObject(strResponse);
			response.setReturnCode(responseObject.getInt("Returncode"));
			if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
				core.setAdditionStatus(true);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return response;
	}

	@Override
	public RegisterResponse register(RegisterRequest request)
			throws JSONException {
		RegisterResponse response = new RegisterResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_REG);
		requestObject.put("Username", request.getUsername());
		String password = MD5Hash.convertPwd(request.getPassword());
		requestObject.put("Password", password);
		requestObject.put("Mobile", request.getPhone());
		Log.e(METHOD_REG, "content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e(METHOD_REG, strResponse);
		JSONObject responseObj = new JSONObject(strResponse);
		response.setReturnCode(responseObj.optInt("Returncode"));
		return response;
	}

	@Override
	public GetAndroidProductResponse getAndroidProductProposed(
			GetAndroidProductProposedRequest request) throws JSONException,
			ClientProtocolException, IOException {
		GetAndroidProductResponse response = new GetAndroidProductResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_GetAndroidProduct);
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("pageNumber", request.getPageNumber());
		requestObject.put("CategoryType", request.getCategoryType());
		requestObject.put("CategoryId", request.getCategoryid());
		requestObject.put("AreaIds", request.getAreaIds());
		requestObject.put("Keywords", request.getKeywords());
		requestObject.put("SortBy", request.getSortBy());
		Log.e("getAndroidProductProposed",
				"content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("getAndroidProductProposed", "" + strResponse);

		JSONObject responseObj = new JSONObject(strResponse);
		response.setReturnCode(responseObj.getInt("Returncode"));
		response.setPageCount(responseObj.getInt("countPage"));
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			JSONArray data = responseObj.getJSONArray("data");
			if (data == null) {
				return response;
			} else {
				ArrayList<ListItemEntity> list_productcatefour = new ArrayList<ListItemEntity>();
				for (int i = 0; i < data.length(); i++) {
					JSONObject json_Obj = data.getJSONObject(i);
					ListItemEntity list_item = parserListItemEntity(json_Obj);
					list_productcatefour.add(list_item);
				}
				response.setListSuggestProduct(list_productcatefour);
			}
		}
		return response;
	}

	@Override
	public GetProductCateFourResponse getProductSubCate(
			GetProductCateFourRequest request) throws JSONException,
			ClientProtocolException, IOException {
		GetProductCateFourResponse response = new GetProductCateFourResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("CategoryType", request.getCategoryType());
		requestObject.put("CategoryId", request.getCategoryId());
		requestObject.put("ItemId", request.getItemId());
		requestObject.put("actionType", METHOD_GetAndroidProduct);
		requestObject.put("pageNumber", request.getPageNumber());
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("SortBy", request.getSortBy());
		requestObject.put("AuthKey", MainApplication.getAuthenKey());
		Log.e("getProductSubCate", "content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("getProductSubCate", "response : " + strResponse);
		JSONObject responseObj = new JSONObject(strResponse);
		response.setReturnCode(responseObj.getInt("Returncode")); // Log.e("returnCode",
		// response.getReturnCode()+"");
		response.setCount(responseObj.getInt("countPage"));
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			int hasmore = responseObj.optInt("HasMore");
			if (hasmore == 1) {
				response.setHasMore(true);
			} else {
				response.setHasMore(false);
			}
			JSONArray data = responseObj.getJSONArray("data");
			if (data == null) {
				return response;
			} else {
				ArrayList<ListItemEntity> list_productcatefour = new ArrayList<ListItemEntity>();
				for (int i = 0; i < data.length(); i++) {
					JSONObject json_Obj = data.getJSONObject(i);
					ListItemEntity list_item = parserListItemEntity(json_Obj);
					list_productcatefour.add(list_item);
				}
				response.setList_productcatefour(list_productcatefour);
			}
		}
		Log.e("response.getList_productcatefour().size()", response
				.getList_productcatefour().size() + "");
		return response;
	}

	@Override
	public ForgotPassResponse forgotPass(ForgetPassRequest request)
			throws JSONException {
		ForgotPassResponse response = new ForgotPassResponse();
		JSONObject requestObj = new JSONObject();
		requestObj.put("actionType", METHOD_FORGOT_PASS);
		if( request.getEmail().contains("@")){
			requestObj.put("Email", request.getEmail());
		}else {
			requestObj.put("UserName", request.getEmail());
		}
		Log.e(METHOD_FORGOT_PASS, "content=" + requestObj.toString());
		String responseStr = callServicePostMethod(URL,
				"content=" + requestObj.toString());
		Log.e(METHOD_FORGOT_PASS, responseStr);
		JSONObject responseObj = new JSONObject(responseStr);
		response.setReturnCode(responseObj.optInt("Returncode"));

		return response;
	}

	@Override
	public GetProfileInfoResponse getProfileInfo(GetProfileInfoRequest request)
			throws JSONException {
		GetProfileInfoResponse response = new GetProfileInfoResponse();
		JSONObject requestObj = new JSONObject();
		requestObj.put("actionType", METHOD_GET_INFO_USER);
		requestObj.put("AuthKey", request.getAuthKey());
		Log.e(METHOD_GET_INFO_USER, "content=" + requestObj.toString());
		String strResponse = callServicePostMethod(URL,
				"content=" + requestObj.toString());
		Log.e(METHOD_GET_INFO_USER, strResponse);
		JSONObject responseObj = new JSONObject(strResponse);
		response.setReturnCode(responseObj.getInt("Returncode"));

		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			JSONObject infoJO = responseObj.optJSONObject("data");
			if (infoJO != null) {
				Hashtable<String, String> values = new Hashtable<String, String>();

				String AreaName = infoJO.optString("AreaName");
				values.put("AreaName", AreaName);
				String Mobile = infoJO.optString("Mobile");
				values.put("Mobile", Mobile);
				String AreaID = infoJO.optString("AreaID");
				values.put("AreaID", AreaID);
				String DisplayName = infoJO.optString("display_name");
				values.put("display_name", DisplayName);
				String UserName = infoJO.optString("username");
				values.put("username", UserName);
				String Email = infoJO.optString("Email");
				values.put("Email", Email);
				String Gender = infoJO.optString("Gender");
				values.put("Gender", Gender);
				String link = infoJO.optString("avatar");
				response.setLink(link);
				response.setInfo(values);
			}
		}
		return response;

	}

	@Override
	public GetAndroidProductTypeResponse getAndroidProductType(
			GetAndroidProductTypeRequest request) throws JSONException,
			ClientProtocolException, IOException {
		GetAndroidProductTypeResponse response = new GetAndroidProductTypeResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_GetAndroidProduct);
		requestObject.put("pageNumber", request.getPageNumber());
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("AuthKey", MainApplication.getAuthenKey());
		requestObject.put("CategoryType", request.getCategoryType());
		requestObject.put("NotInPCodes", request.getNotInPCodes());
		if (request.isStore() == true) {
			requestObject.put("CategoryId", request.getCategoryid());
			requestObject
			.put("GuaranteeStoreId", request.getGuaranteeStoreID());
		} else {
			requestObject.put("CategoryId", request.getCategoryid());
		}
		requestObject.put("ItemId", request.getItemId());
		Log.e("getAndroidProductType", "content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("getAndroidProductType", "" + strResponse);
		JSONObject responseObj = new JSONObject(strResponse);
		response.setReturnCode(responseObj.getInt("Returncode"));
		response.setPageCount(responseObj.getInt("countPage"));
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			JSONArray dataResponse = responseObj.getJSONArray("data");
			int hasmore = responseObj.getInt("HasMore");
			if (hasmore == 1) {
				response.setHasMore(true);
			} else {
				response.setHasMore(false);
			}
			// response.setHasMore(responseObj.optBoolean("HasMore"));
			if (dataResponse == null) {
				return response;
			} else {
				ArrayList<ListItemEntity> list_product = new ArrayList<ListItemEntity>();
				for (int i = 0; i < dataResponse.length(); i++) {
					JSONObject item = dataResponse.getJSONObject(i);
					ListItemEntity entity = parserListItemEntity(item);
					list_product.add(entity);
				}
				response.setListProductType(list_product);
			}
		}
		return response;
	}

	@Override
	public ProductBySellerRespone getProductbySeller(
			ProductBySellerRequest request) throws JSONException,
			ClientProtocolException, IOException {
		ProductBySellerRespone reponse = new ProductBySellerRespone();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_GetAndroidProduct);
		requestObject.put("CategoryType", request.getCategoryType());
		requestObject.put("Username", request.getSellerName());
		requestObject.put("ItemId", request.getItemId());
		requestObject.put("pageNumber", request.getPageNumber());
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("AuthKey", authenKeyAPI);
		requestObject.put("NotInPCodes", request.getNotInPCodes());
		if (request.getGuaranteeId() > 0) {
			requestObject.put("GuaranteeStoreId", request.getGuaranteeId());
			requestObject.put("CategoryId", request.getCategoryId());

		}
		Log.e("getProductSuppliers1", "content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("getProductSuppliers1", strResponse);
		JSONObject reponseObject = new JSONObject(strResponse);
		reponse.setReturnCode(reponseObject.getInt("Returncode"));
		if (reponse.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			int hasmore = reponseObject.optInt("HasMore");
			if (hasmore == 1) {
				reponse.setHasmore(true);
			} else {
				reponse.setHasmore(false);
			}
			JSONArray adsJA = reponseObject.optJSONArray("data");
			if (adsJA == null) {
				return reponse;
			}
			ArrayList<ListItemEntity> item = new ArrayList<ListItemEntity>();
			for (int i = 0; i < adsJA.length(); i++) {
				JSONObject adJO = adsJA.optJSONObject(i);
				ListItemEntity ade = parserListItemEntity(adJO);
				item.add(ade);
			}
			reponse.setListItemEntity(item);
		}
		return reponse;
	}

	@Override
	public CommentResponseProduct getCommentProduct(
			CommentRequestProduct request) throws JSONException,
			ClientProtocolException, IOException {
		CommentResponseProduct response = new CommentResponseProduct();
		JSONObject requestObj = new JSONObject();
		requestObj.put("actionType", "getItemDetail");
		requestObj.put("ItemId", request.getItemId());
		requestObj.put("AuthKey", MainApplication.getAuthenKey());
		Log.e("getCommentProduct", "content=" + requestObj.toString());
		String jsonReponse = callServicePostMethod(URL,
				"content=" + requestObj.toString());
		Log.e("getCommentProduct", jsonReponse);

		JSONObject responseObject = new JSONObject(jsonReponse);
		response.setReturnCode(responseObject.getInt("Returncode"));
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			JSONObject jsonObj = responseObject
					.getJSONObject("ItemEntityDetail");
			JSONArray jsonArr = jsonObj.getJSONArray("CommentInfo");
			ArrayList<CommentEntity> listComment = new ArrayList<CommentEntity>();
			if (jsonArr != null) {
				for (int i = 0; i < jsonArr.length(); i++) {
					JSONObject obj = jsonArr.getJSONObject(i);
					CommentEntity entity = parserCommentEntity(obj);
					listComment.add(entity);
				}
			}
			response.setListComment(listComment);
			JSONObject jsonObjRating = jsonObj.optJSONObject("RatingInfo");
			if (jsonObjRating != null) {
				JSONArray jsonArrUserRating = jsonObjRating.getJSONArray("ListUserRating");
				if (jsonArrUserRating != null){
					ArrayList<RatingUserEntity> listUserRating = new ArrayList<RatingUserEntity>();
					for (int j=0;j<jsonArrUserRating.length();j++){
						JSONObject objrating = jsonArrUserRating.getJSONObject(j);
						JSONObject objvalue = objrating.optJSONObject("RatingUser");
						RatingUserEntity entity = new RatingUserEntity();
						String value = null;
						value = objvalue.optString("Value");
						if (value != null) {
							entity.setValue(value);
						}
						value = objvalue.optString("UserName");
						if (value != null) {
							entity.setUserName(value);
						}
						listUserRating.add(entity);
					}
					response.setArrRating(listUserRating);
				}

				RatingInfo rating = new RatingInfo();
				try {
					rating.setAverage(jsonObjRating.getInt("Average"));
					rating.setExcellent(jsonObjRating.getInt("Excellent"));
					rating.setPoor(jsonObjRating.getInt("Poor"));
					rating.setTerrible(jsonObjRating.getInt("Terrible"));
					rating.setVerygood(jsonObjRating.getInt("VeryGood"));
					rating.setTotalCount(jsonObjRating.getInt("TotalCount"));
					rating.setRating(jsonObjRating.getInt("Rating"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
				response.setListofRating(rating);
			}
			String Description = jsonObj.getString("Description");
			response.setDescription(Description);
		}

		return response;
	}

	@Override
	public GetAndroidInterestShopResponse getAndroidInterestShop(
			GetAndroidInterestShopRequest request) throws JSONException,
			ClientProtocolException, IOException {
		// TODO Auto-generated method stub
		GetAndroidInterestShopResponse response = new GetAndroidInterestShopResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_GetAndroidInterestShop);
		requestObject.put("AuthKey", MainApplication.getAuthenKey());
		requestObject.put("ItemId", request.getGuaranteStoreId());
		requestObject.put("UserName", request.getUserName());
		requestObject.put("Type", request.getType());
		Log.e("GetAndroidIntertest", "Request : " + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("GetAndroidIntertest", "strResponse: " + strResponse);
		JSONObject responseObject = new JSONObject(strResponse);
		response.setReturnCode(responseObject.optInt("Returncode"));
		int value = responseObject.optInt("isInterest");
		if (value == 1) {
			response.setInterest(true);
		} else {
			response.setInterest(false);
		}
		return response;
	}

	@Override
	public SendAndroidInterestShopResponse sendAndroidInterestShop(
			SendAndroidInterestShopRequest request) throws JSONException,
			ClientProtocolException, IOException {
		SendAndroidInterestShopResponse response = new SendAndroidInterestShopResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_SendAndroidInterestShop);
		requestObject.put("AuthKey", request.getAuthenKey());
		requestObject.put("ItemId", request.getGuaranteStoreId());
		requestObject.put("UserName", request.getUserName());
		requestObject.put("IsInterest", request.getIsInterest());
		requestObject.put("Type", request.getType());
		Log.e("SendAndroidIntertest", "content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("SendAndroidIntertest", "strResponse: " + strResponse);
		JSONObject responseObject = new JSONObject(strResponse);
		response.setReturnCode(responseObject.optInt("Returncode"));
		return response;
	}

	@Override
	public CommentResponse comment(CommentRequest request)
			throws JSONException, ClientProtocolException, IOException {
		CommentResponse response = new CommentResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_Comment);
		requestObject.put("AuthKey", MainApplication.getAuthenKey());
		requestObject.put("ItemId", request.getItemId());
		requestObject.put("Message", request.getMessage());
		requestObject.put("UserName", request.getUserName());
		if (request.isComment() == true) {
			requestObject.put("Rating", 0);
		} else {
			requestObject.put("Rating", request.getRating());
		}
		requestObject.put("MessageTitle", request.getMessageTitle());
		requestObject.put("CommentDate", request.getTimeComment());
		requestObject.put("Type", request.getType());

		Log.e("Sent Comment", "content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		JSONObject responseObject = new JSONObject(strResponse);
		Log.e("Sent Comment", " ReturnString" + responseObject.toString());
		response.setReturnCode(responseObject.getInt("Returncode"));
		response.setResultMsg(responseObject.getString("resultMsg"));
		return response;
	}

	@Override
	public SendAndroidProductAbuselResponse sendAndroidProductAbusel(
			SendAndroidProductAbuselRequest request) throws JSONException,
			ClientProtocolException, IOException {
		SendAndroidProductAbuselResponse reponse = new SendAndroidProductAbuselResponse();
		JSONObject requestObj = new JSONObject();
		requestObj.put("actionType", METHOD_SendAndroidProductAbusel);
		requestObj.put("ProductID", request.getProductID());
		requestObj.put("Message", request.getMessage());
		Log.e("SendAndroidProductAbusel", "content=" + requestObj.toString());
		String strResponse = callServicePostMethod(URL,
				"content=" + requestObj.toString());
		JSONObject responseObject = new JSONObject(strResponse);
		Log.e("SendAndroidProductAbusel", " " + strResponse);
		reponse.setReturnCode(responseObject.getInt("Returncode"));
		reponse.setResultMsg(responseObject.getString("resultMsg"));
		return reponse;
	}

	@Override
	public UploadPictureResponse uploadPicture(UploadPictureRequest request,
			String content) throws JSONException, ClientProtocolException,
			IOException {
		UploadPictureResponse response = new UploadPictureResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_uploadPicture);
		requestObject.put("AuthKey", request.getAuthKey());
		requestObject.put("Content", request.getContent());
		String strRequest = "";
		if (request.getType() == 1){
			strRequest = "content={\"actionType\":\"uploadPicture\",\"AuthKey\":\"62741bde8d0be250ad74fdd49968a925\",\"Type\":1,\"Content\":\""
					+ content + "\"}";
		}else{
			strRequest = "content={\"actionType\":\"uploadPicture\",\"AuthKey\":\"62741bde8d0be250ad74fdd49968a925\",\"Content\":\""+ content + "\"}";
		}

		Log.d("request", strRequest);
		strRequest = strRequest.replace("62741bde8d0be250ad74fdd49968a925",
				request.getAuthKey());

		String strResponse = callServicePostMethod(URL, strRequest);
		strResponse.replace("\\", "");

		JSONObject responseObject = new JSONObject(strResponse);
		Log.d("TEST", "strResponse = " + strResponse);
		response.setReturnCode(responseObject.getInt("Returncode"));
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			response.setFileName(responseObject.optString("FileName"));
		}
		return response;
	}

	@Override
	public PublishResponse publish(PublishRequest request)
			throws JSONException, ClientProtocolException, IOException {
		PublishResponse response = new PublishResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_Publish);
		if (!authenKeyAPI.equals("")) {
			requestObject.put("AuthKey", authenKeyAPI);
		}
		JSONArray imagesJA = new JSONArray();

		if (request.getImages().isEmpty()) {
			JSONObject paramsObject = new JSONObject();
			paramsObject.put("name", "no_image.png");
			paramsObject.put("pixel", "0*0");
			imagesJA.put(paramsObject);
		} else {
			for (String name : request.getImages()) {
				JSONObject paramsObject = new JSONObject();
				paramsObject.put("name", name);
				paramsObject.put("pixel", "0*0");
				imagesJA.put(paramsObject);
			}
		}

		requestObject.put("Images", imagesJA);
		requestObject.put("Content", request.getContent());
		requestObject.put("CreateBy", request.getCreateBy());

		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.d("TEST", "publish request = " + requestObject.toString());
		Log.d("TEST", "publish response = " + strResponse);
		JSONObject responseObject = new JSONObject(strResponse);
		response.setReturnCode(responseObject.getInt("Returncode"));
		response.setPublishId(responseObject.optString("PublishId"));
		return response;
	}

	@Override
	public LogoutResponse finishLogout(LogoutRequest request)
			throws JSONException, IOException, ClientProtocolException {
		LogoutResponse response = new LogoutResponse();
		JSONObject requestObj = new JSONObject();
		requestObj.put("actionType", METHOD_LOG_OUT);
		requestObj.put("AuthKey", MainApplication.getAuthenKey());
		Log.e(METHOD_LOG_OUT, "content=" + requestObj.toString());
		String strReponse = callServicePostMethod(URL,
				"content=" + requestObj.toString());
		Log.e(METHOD_LOG_OUT, strReponse);
		JSONObject responseObj = new JSONObject(strReponse);
		response.setResultCode(responseObj.optString("resultMsg"));
		response.setReturnCode(responseObj.optInt("Returncode"));
		return response;
	}

	@Override
	public GetMyHandBookResponse getMyHandBook(GetMyHandBookRequest request)
			throws JSONException, ClientProtocolException, IOException {
		// TODO Auto-generated method stub
		GetMyHandBookResponse response = new GetMyHandBookResponse();
		JSONObject requestObject = new JSONObject();
		if (request.getType() == 1) {
			requestObject.put("actionType", METHOD_GetFavorites);
			//			requestObject.put("Username", request.getUserName());
			requestObject.put("UserID", request.getUserId());
			requestObject.put("Type", "products");
			requestObject.put("contain",new JSONArray("[\"Product\"]") );
			requestObject.put("pageLimit", request.getPageLimit());
			requestObject.put("pageNumber", request.getPageNumber());
			requestObject.put("AuthKey", request.getAuthKey());
		} else if (request.getType() == 2) {
			requestObject.put("actionType", METHOD_GetMyPosted);
			requestObject.put("UserId", request.getUserId());
			requestObject.put("pageLimit", request.getPageLimit());
			requestObject.put("pageNumber", request.getPageNumber());
			requestObject.put("AuthKey", request.getAuthKey());
		} else {
			requestObject.put("actionType", METHOD_GetHistory);
			requestObject.put("Keywords","");
			requestObject.put("InIDs", new JSONArray(request.getHistoryId()));
			requestObject.put("CategoryType", "products");
			requestObject.put("pageLimit", request.getPageLimit());
			requestObject.put("pageNumber", request.getPageNumber());
		}
		Log.e("My HandBook", "Request : " + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("My HandBook", "strResponse: " + strResponse);
		JSONObject responseObject = new JSONObject(strResponse);
		response.setReturnCode(responseObject.optInt("Returncode"));

		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			JSONArray dataResponse;
			if (request.getType() == 1 || request.getType() == 3 ) {
				dataResponse	 = responseObject.optJSONArray("data");
			}else{
				dataResponse = responseObject.optJSONArray("Items");
			}
			int hasmore = responseObject.optInt("HasMore");
			if (hasmore == 1) {
				response.setHasMore(true);
			} else {
				response.setHasMore(false);
			}
			int pagecount = responseObject.optInt("countPage");

			response.setPageCount(pagecount);

			if (dataResponse == null) {
				return response;
			} else {
				ArrayList<ListItemEntity> listproduct = new ArrayList<ListItemEntity>();
				for (int i = 0; i < dataResponse.length(); i++) {
					JSONObject productObj = dataResponse.getJSONObject(i);
					ListItemEntity entity = parserListItemEntity(productObj);
					listproduct.add(entity);
				}
				response.setListItemEntities(listproduct);
			}
		}

		return response;
	}

	@Override
	public ChangePassResponse finishChangePass(ChangePassRequest request)
			throws JSONException, IOException, ClientProtocolException {
		ChangePassResponse response = new ChangePassResponse();
		JSONObject requestObj = new JSONObject();
		requestObj.put("actionType", METHOD_CHANGE_PASS);
		requestObj.put("AuthKey", request.getAuthKey());
		String oldpass = MD5Hash.convertPwd(request.getOldPass());
		String newpass = MD5Hash.convertPwd(request.getNewPass());
		requestObj.put("OldPassword", oldpass);
		requestObj.put("NewPassword", newpass);
		Log.e(METHOD_CHANGE_PASS, "content=" + requestObj.toString());
		String strReponse = callServicePostMethod(URL,
				"content=" + requestObj.toString());
		Log.e(METHOD_LOG_OUT, strReponse);
		JSONObject responseObj = new JSONObject(strReponse);
		response.setRessultMsg(responseObj.optString("resultMsg"));
		response.setReturnCode(responseObj.optInt("Returncode"));
		return response;
	}

	@Override
	public UpdateUserInfoResponse finishUpdateUserInfo(
			UpdateUserInfoRequest request) throws JSONException,
			ClientProtocolException, IOException {
		UpdateUserInfoResponse response = new UpdateUserInfoResponse();
		JSONObject requestObj = new JSONObject();
		requestObj.put("actionType", METHOD_UPDATE_USER_INFO);
		requestObj.put("AuthKey", request.getAuthenKey());
		requestObj.put("display_name", request.getDisplayName());
		requestObj.put("Gender", request.getGender());
		requestObj.put("area_id", request.getArea());
		requestObj.put("Mobile", request.getPhone());
		if (!TextUtils.isEmpty(request.getEmail())){
			requestObj.put("Email", request.getEmail());
		}
		Log.e(METHOD_UPDATE_USER_INFO, "content=" + requestObj.toString());
		String strReponse = callServicePostMethod(URL,
				"content=" + requestObj.toString());
		Log.e(METHOD_LOG_OUT, strReponse);
		JSONObject responseObj = new JSONObject(strReponse);
		response.setReturnCode(responseObj.optInt("Returncode"));
		return response;
	}

	@Override
	public String finishUpdateView(String request) throws JSONException,
	ClientProtocolException, IOException {
		String reponse = new String();
		JSONObject requestObj = new JSONObject();
		requestObj.put("actionType", METHOD_UPDATE_VIEW_PRODUCT);
		requestObj.put("PCode", request);
		String strReponse = callServicePostMethod(URL,
				"content=" + requestObj.toString());
		Log.e("UPDATE VIEW", "content=" + requestObj.toString());
		JSONObject responseObj = new JSONObject(strReponse);
		reponse = responseObj.optString("resultMsg");
		Log.e("UPDATE VIEW", reponse + " .");
		return reponse;
	}

	@Override
	public SearchResponse getGlobalSearch(
			GetSearchGlobalProductRequest request) throws JSONException,
			ClientProtocolException, IOException {
		SearchResponse reponse = new SearchResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_Search);
		requestObject.put("AuthKey", authenKeyAPI);
		requestObject.put("AreaIds", request.getAreaIds());
		requestObject.put("IsDisabled", request.getIsDisable());
		requestObject.put("CategoryType", request.getCategoryType());
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("pageNumber", request.getPageNumber());
		requestObject.put("Keywords", request.getKeywords());
		if (request.getCategoryId() != null){
			requestObject.put("CategoryId", request.getCategoryId());
		}
		Log.e("searchGlobalProduct", "content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("searchGlobalProduct", strResponse);
		JSONObject reponseObject = new JSONObject(strResponse);
		reponse.setReturnCode(reponseObject.getInt("Returncode"));
		if (reponse.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			reponse.setPageCount(reponseObject.getInt("countPage"));
			JSONArray adsJA = reponseObject.optJSONArray("data");
			if (adsJA == null) {
				return reponse;
			}
			ArrayList<ListItemEntity> item = new ArrayList<ListItemEntity>();
			for (int i = 0; i < adsJA.length(); i++) {
				JSONObject adJO = adsJA.optJSONObject(i);
				ListItemEntity ade = parserListItemEntity(adJO);
				item.add(ade);
			}
			reponse.setItems(item);
		}
		return reponse;
	}

	@Override
	public GetAndroidProductTypeResponse getAndroidProductSameCost(
			GetAndroidProductTypeRequest request) throws JSONException,
			ClientProtocolException, IOException {
		GetAndroidProductTypeResponse response= new GetAndroidProductTypeResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_GetAndroidProduct);
		requestObject.put("pageNumber", request.getPageNumber());
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("AuthKey", MainApplication.getAuthenKey());
		requestObject.put("CategoryType", request.getCategoryType());
		requestObject.put("SamePrice", request.getSameCost());
		requestObject.put("NotInPCodes", request.getNotInPCodes());
		if (request.isStore() == true) {
			requestObject.put("CategoryId", request.getCategoryid());
			requestObject
			.put("GuaranteeStoreId", request.getGuaranteeStoreID());
		} else {
			requestObject.put("CategoryId", request.getCategoryid());
		}
		requestObject.put("ItemId", request.getItemId());
		Log.e("getAndroidProductType", "content=" + requestObject.toString());
		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.e("getAndroidProductType", "" + strResponse);
		JSONObject responseObj = new JSONObject(strResponse);
		response.setReturnCode(responseObj.getInt("Returncode"));
		response.setPageCount(responseObj.getInt("countPage"));
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			JSONArray dataResponse = responseObj.getJSONArray("data");
			int hasmore = responseObj.getInt("HasMore");
			if (hasmore == 1) {
				response.setHasMore(true);
			} else {
				response.setHasMore(false);
			}
			// response.setHasMore(responseObj.optBoolean("HasMore"));
			if (dataResponse == null) {
				return response;
			} else {
				ArrayList<ListItemEntity> list_product = new ArrayList<ListItemEntity>();
				for (int i = 0; i < dataResponse.length(); i++) {
					JSONObject item = dataResponse.getJSONObject(i);
					ListItemEntity entity = parserListItemEntity(item);
					list_product.add(entity);
				}
				response.setListProductType(list_product);
			}
		}
		return response;
	}

	@Override
	public ChangeAvatarResponse ChangeAvatar(ChangeAvatarRequest request)
			throws JSONException, ClientProtocolException, IOException {
		// TODO Auto-generated method stub
		ChangeAvatarResponse response = new ChangeAvatarResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_UPDATE_USER_INFO);
		requestObject.put("AuthKey", request.getAthkey());
		requestObject.put("display_picture", request.getDisplayPicture());
		requestObject.put("area_id", request.getArea());

		String strResponse = callServicePostMethod(URL, "content="
				+ requestObject.toString());
		Log.d("TEST", "changeAVATAR request = " + requestObject.toString());
		Log.d("TEST", "changeAVATAR response = " + strResponse);
		JSONObject responseObject = new JSONObject(strResponse);
		response.setReturnCode(responseObject.getInt("Returncode"));
		response.setResultmsg(responseObject.getString("resultMsg"));
		return response;
	}
}
